package com.ry.novel.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ry.novel.mapper.NewsMapper;
import com.ry.novel.model.dto.NewsInfo;
import com.ry.novel.model.entity.News;
import com.ry.novel.service.NewsService;
import com.ry.novel.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author ry
 * @since 2022-04-20 21:35
 **/
@Service
public class NewsServiceImpl implements NewsService {

    @Autowired
    private NewsMapper newsMapper;

    @Override
    public List<NewsInfo> queryNewsByDateDesc() {
        Page<News> page = new Page<>(1, 3);
        QueryWrapper<News> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("create_time");

        newsMapper.selectPage(page, wrapper);

        List<NewsInfo> infos = page.getRecords().stream().map(entity -> {
            NewsInfo newsInfo = new NewsInfo();
            newsInfo.setId(entity.getId());
            newsInfo.setTitle(entity.getTitle());
            newsInfo.setContent(entity.getContent());
            newsInfo.setReadCount(entity.getReadCount());
            newsInfo.setCreateTime(DateUtil.format(entity.getCreateTime()));
            newsInfo.setUpdateTime(DateUtil.format(entity.getUpdateTime()));


            return newsInfo;
        }).collect(Collectors.toList());


        return infos;
    }

    @Override
    public NewsInfo queryNewsById(Long id) {
        News entity = newsMapper.selectById(id);
        NewsInfo newsInfo = new NewsInfo();
        newsInfo.setId(entity.getId());
        newsInfo.setTitle(entity.getTitle());
        newsInfo.setContent(entity.getContent());
        newsInfo.setReadCount(entity.getReadCount());
        newsInfo.setCreateTime(DateUtil.format(entity.getCreateTime()));
        newsInfo.setUpdateTime(DateUtil.format(entity.getUpdateTime()));

        return newsInfo;
    }
}
